// #pragma execution_character_set("utf-8")
#include "vsgUI.h"
#include "CornerGrid.h"
#include "ProgressDlg.h"
#include "Worker.h"
#include "well.h"
#include <QCheckBox>
#include <QFileDialog>
#include <QMessageBox>
#include <QMouseEvent>

vsgUI* gUI = nullptr;

vsgUI::vsgUI(QWidget* parent) : QMainWindow(parent)
{
  qRegisterMetaType<SelectField>("SelectField");
  ui.setupUi(this);
  QWidget* centralwidget = new QWidget(this);
  centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
  QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  centralwidget->setSizePolicy(sizePolicy);
  this->setCentralWidget(centralwidget);
  mLayout = new QVBoxLayout(centralwidget);
  centralwidget->setLayout(mLayout);
  ui.dockWidget->setFeatures(QDockWidget::NoDockWidgetFeatures);

  connect(ui.actionOpen, &QAction::triggered, this, &vsgUI::OpenFile);
  connect(ui.actionOpenWell, &QAction::triggered, this, &vsgUI::OpenWell);

  connect(ui.SwapColorTexture, SIGNAL(clicked()), this, SLOT(SwapTexutre()));
  connect(ui.SwapColorTexture_2, SIGNAL(clicked()), this, SLOT(SwapTexutre2()));

  // connect(ui.Apply, SIGNAL(clicked()), this, SLOT(Apply()));

  // connect(ui.ShowGrid, SIGNAL(clicked()), this, SLOT(ShowGrid()));

  connect(ui.RemoveGrid, SIGNAL(clicked()), this, SLOT(RemoveGridLayer()));
  connect(ui.RemoveWell, SIGNAL(clicked()), this, SLOT(RemoveWellLayer()));
  connect(ui.RemoveAll, SIGNAL(clicked()), this, SLOT(RemoveCurrentAll()));

  connect(ui.TransSlider, &QSlider::valueChanged, this, &vsgUI::SetAlpha);
  ui.TransSlider->setMaximum(100);
  ui.TransSlider->setValue(0);

  // connect(ui.comboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &vsgUI::ComboxTimeStepChange);
  connect(ui.comboBox_Value, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &vsgUI::ComboxFieldChange);

  // ui.ValueShowChange->setSelectionMode(QAbstractItemView::SingleSelection);
  // ui.Name_LocWidget->setSelectionMode(QAbstractItemView::MultiSelection);

  // QListWidgetItem* titleItem = new QListWidgetItem("可选择属性");
  // titleItem->setFlags(titleItem->flags() & ~Qt::ItemIsSelectable);  // 使标题不可选
  // titleItem->setBackground(Qt::lightGray);                     // 设置标题背景色
  // ui.Name_LocWidget->addItem(titleItem);

  // QListWidgetItem* titleItem2 = new QListWidgetItem("可切换属性");
  // titleItem2->setFlags(titleItem2->flags() & ~Qt::ItemIsSelectable);  // 使标题不可选
  // titleItem2->setBackground(Qt::lightGray);                          // 设置标题背景色
  // ui.ValueShowChange->addItem(titleItem2);

  QDoubleValidator* doubleValidator = new QDoubleValidator(0.0001, 1000.0, 2);
  ui.lineEditSZ->setValidator(doubleValidator);

  connect(ui.radioButtonStatic, SIGNAL(toggled(bool)), this, SLOT(SetStaticOrDynamic(bool)));
  connect(ui.radioButtonDynamic, SIGNAL(toggled(bool)), this, SLOT(SetStaticOrDynamic(bool)));
  ui.radioButtonStatic->setChecked(true);

  mColorTable1 = "Assest/color.bmp";
  mColorTable2 = "Assest/color2.png";

  connect(ui.label1, SIGNAL(clicked()), this, SLOT(SetTexture1));
  connect(ui.label2, SIGNAL(clicked()), this, SLOT(SetTexture2));

  ui.label1->installEventFilter(this);
  ui.label2->installEventFilter(this);

  ui.label1->resize(QSize(256, 50));
  ui.label2->resize(QSize(256, 50));

  QPixmap map1(mColorTable1);
  ui.label1->setPixmap(map1.scaled(ui.label1->size()));
  ui.label1->show();

  QPixmap map2(mColorTable2);
  ui.label2->setPixmap(map2.scaled(ui.label2->size()));
  ui.label2->show();

  progressBar = new QProgressBar(this);
  progressBar->setRange(0, 100);
  progressBar->setValue(0);
  progressBar->setAlignment(Qt::AlignCenter);
  progressBar->setFormat(QString::fromUtf8(""));
  progressBar->setFixedWidth(200);
  progressBar->setFixedHeight(20);

  mpStateMessageLabel = new QLabel();
  mpStateMessageLabel->setText(QString::fromUtf8(""));
  mp3DMessageLabel = new QLabel();
  mp3DMessageLabel->setText(QString::fromUtf8(""));
  ui.statusBar->addWidget(progressBar);
  ui.statusBar->addWidget(mpStateMessageLabel);
  ui.statusBar->addPermanentWidget(mp3DMessageLabel);  // 添加到状态栏的右边
  ui.checkBoxPick->setCheckState(Qt::CheckState::Checked);

  // QVBoxLayout* layout = new QVBoxLayout(ui.groupBoxAlpha);
  // mRangeSlider        = new RangeSlider(Qt::Horizontal, RangeSlider::Option::DoubleHandles, ui.groupBoxAlpha);
  // layout->addWidget(mRangeSlider);
  // QPushButton* button = new QPushButton();
  // button->resize(QSize(100, 50));
  // button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  // button->setText(QString::fromUtf8("测试应用"));
  // connect(button, SIGNAL(clicked()), this, SLOT(FilterDebug()));
  // connect(ui.pushButtonFilter2, SIGNAL(clicked()), this, SLOT(Filter2()));
  // layout->addWidget(button);
  // ui.groupBoxAlpha->setLayout(layout);

  // connect(ui.SelAll_I, SIGNAL(clicked()), this, SLOT(SelAll_I()));
  // connect(ui.SelAll_J, SIGNAL(clicked()), this, SLOT(SelAll_J()));
  // connect(ui.SelAll_K, SIGNAL(clicked()), this, SLOT(SelAll_K()));
  // connect(ui.RSel_I, SIGNAL(clicked()), this, SLOT(ReSel_I()));
  // connect(ui.RSel_J, SIGNAL(clicked()), this, SLOT(ReSel_J()));
  // connect(ui.RSel_K, SIGNAL(clicked()), this, SLOT(ReSel_K()));
  // connect(ui.FilterApply, SIGNAL(clicked()), this, SLOT(Filter()));

  // ui.groupBox_Filter1->setVisible(false);
  // ui.groupBox_Filter2->setVisible(false);
  // ui.checkBoxResetCamera->setVisible(false);
  // ui.groupBox_7->setVisible(false);

  connect(ui.ResetScene, SIGNAL(clicked()), this, SLOT(ResetScene()));
  // connect(ui.ClearScene, SIGNAL(clicked()), this, SLOT(ClearScene()));

  connect(ui.ApplyFilter3, SIGNAL(clicked()), this, SLOT(Filter3()));
  // connect(ui.ApplyFilter4, SIGNAL(clicked()), this, SLOT(Filter4()));

  // 创建一个整数验证器，最小值为1（表示只能输入正整数）
  QIntValidator* validator = new QIntValidator(0, INT_MAX, ui.lineEdit_StartI);
  ui.lineEdit_StartI->setValidator(validator);
  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_StartJ);
  ui.lineEdit_StartJ->setValidator(validator);
  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_StartK);
  ui.lineEdit_StartK->setValidator(validator);

  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_IStep);
  ui.lineEdit_IStep->setValidator(validator);
  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_JStep);
  ui.lineEdit_JStep->setValidator(validator);
  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_KStep);
  ui.lineEdit_KStep->setValidator(validator);

  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_EndI);
  ui.lineEdit_EndI->setValidator(validator);
  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_EndJ);
  ui.lineEdit_EndJ->setValidator(validator);
  validator = new QIntValidator(0, INT_MAX, ui.lineEdit_EndK);
  ui.lineEdit_EndK->setValidator(validator);

  ui.lineEdit_EndI->setEnabled(false);
  ui.lineEdit_EndJ->setEnabled(false);
  ui.lineEdit_EndK->setEnabled(false);

  ui.lineEdit_StartI->setEnabled(false);
  ui.lineEdit_StartJ->setEnabled(false);
  ui.lineEdit_StartK->setEnabled(false);

  ui.lineEdit_IStep->setEnabled(false);
  ui.lineEdit_JStep->setEnabled(false);
  ui.lineEdit_KStep->setEnabled(false);
  connect(ui.checkBox_FilterI, SIGNAL(toggled(bool)), this, SLOT(SelFilterI(bool)));
  connect(ui.checkBox_FilterJ, SIGNAL(toggled(bool)), this, SLOT(SelFilterJ(bool)));
  connect(ui.checkBox_FilterK, SIGNAL(toggled(bool)), this, SLOT(SelFilterK(bool)));

  connect(ui.FilterRestore, SIGNAL(clicked()), this, SLOT(FilterReset()));

  // 连接 returnPressed 信号与槽函数
  connect(ui.lineEditSZ, SIGNAL(returnPressed()), this, SLOT(Apply()));
  // connect(ui.lineEditSZ, &QLineEdit::editingFinished, this, &vsgUI::Apply);

  connect(ui.lineEditLightSrength, SIGNAL(returnPressed()), this, SLOT(LightSrengthUpdate()));
  QDoubleValidator* doubleValidator2 = new QDoubleValidator(0.0, 5.0, 2);
  ui.lineEditLightSrength->setValidator(doubleValidator2);

  connect(ui.lineEditGridSeeDistance, SIGNAL(returnPressed()), this, SLOT(SetGridSeeDistance()));
  connect(ui.checkBoxGridLine, SIGNAL(toggled(bool)), this, SLOT(SetGridLineShow(bool)));
  ui.checkBoxGridLine->setChecked(true);

  QDoubleValidator* doubleValidator22 = new QDoubleValidator(this);
  // 设置允许的数值范围和小数点后的位数
  doubleValidator22->setRange(1, 10000000.0, 2);
  // 将验证器应用到QLineEdit上
  ui.lineEditGridSeeDistance->setValidator(doubleValidator22);

  gUI = this;

  ui.FileTreeView->header()->hide();
  // 创建模型
  mTreeModel = new QStandardItemModel();
  // 创建根节点
  mTreeRoot = new QStandardItem("网格数据");
  mTreeRoot->setIcon(QIcon(":/vsgUI/Scene.png"));
  mTreeModel->appendRow(mTreeRoot);

  mTreeRootWell = new QStandardItem("井数据");
  mTreeRootWell->setIcon(QIcon(":/vsgUI/well.png"));
  mTreeModel->appendRow(mTreeRootWell);

  // 创建 TreeView 并设置模型
  ui.FileTreeView->setModel(mTreeModel);
  ui.FileTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
  connect(ui.FileTreeView, &QTreeView::customContextMenuRequested, this, &vsgUI::onCustomContextMenuRequested);
  connect(ui.FileTreeView, &QTreeView::clicked, this, &vsgUI::TreeSelect);
}

vsgUI::~vsgUI() {}

void vsgUI::ShowStateMessageAndProgress(QString msg, float per)
{
  // mpStateMessageLabel->setText(msg);
  // ui.progressBar->setValue(per);
  // ui.progressBar->setFormat(QString("%1").arg((int)per));
}

bool vsgUI::eventFilter(QObject* watched, QEvent* event)
{
  if (watched == this->ui.label1)
  {
    // 判断事件类型是否为鼠标事件
    if (event->type() == QEvent::MouseButtonPress)
    {
      SetTexture1();
    }
  }
  if (watched == this->ui.label2)
  {
    // 判断事件类型是否为鼠标事件
    if (event->type() == QEvent::MouseButtonPress)
    {
      SetTexture2();
    }
  }
  return QMainWindow::eventFilter(watched, event);
}
bool vsgUI::GetPick()
{
  return ui.checkBoxPick->checkState() == Qt::CheckState::Checked;
}
void vsgUI::ShowPickMessage(vsg::ivec3 ijk, vsg::dvec3 location)
{
  vsg::dvec3 offset(0, 0, 0);
  double dV = InvalidValue;
  if (mpWorker)
  {
    offset = mpWorker->GetOffset();
    offset = offset + mpWorker->GetCenterOffset();
    dV     = mpWorker->GetValue(ui.comboBox_Value->currentIndex(), ijk);
  }
  QString msg = QString("坐标(%1,%2,%3),编号(%4,%5,%6),属性(%7)")
                  .arg(location.x + offset.x)
                  .arg(location.y + offset.y)
                  .arg(location.z + offset.z)
                  .arg(ijk.x)
                  .arg(ijk.y)
                  .arg(ijk.z)
                  .arg(dV);
  if (m3DRender)
  {
    m3DRender->HighLightShowGridCell(ijk);
  }
  mp3DMessageLabel->setText(msg);
}

void vsgUI::ShowGrid()
{
  ui.comboBox_Value->clear();
  for (int k = 0; k < mSelectField.size(); ++k)
  {
    if (mSelectField[k].id > 0)
    {
      ui.comboBox_Value->addItem(mSelectField[k].time + "_" + mSelectField[k].field);
    }
    else
    {
      ui.comboBox_Value->addItem(mSelectField[k].field);
    }
  }
  m3DRender->RemoveRenderNode(mCurrentNode);
  if (mpWorker)
  {
    mpWorker->SetGridPathAndField(mGridPath, mSelectField);
    mpWorker->SetWorkType(2);
    mpWorker->start();
  }
}

void vsgUI::Init3D()
{
  m3DRender = new Dream3DRender(this);
  mLayout->addWidget(m3DRender->Initialization());
}

void vsgUI::SwapTexutre()
{
  if (m3DRender)
  {
    m3DRender->SetTextureColorTable(mColorTable1);
  }
}

void vsgUI::GetTable()
{
  // if (mpWorker)
  //{
  //   // 数据初始化完了  获取属性相关信息
  //   if (mpWorker->WorkType() == 1)
  //   {
  //     std::vector<std::vector<Name_Loc>> table = mpWorker->GetDynamicTable();
  //     // timeStep   att
  //     for (int k = 0; k < table.size(); ++k)
  //     {
  //       ui.comboBox->addItem(QString("%1").arg(k + 1));
  //     }
  //   }
  // }
}

void vsgUI::ComboxTimeStepChange(int index)
{
  // if (mpWorker == nullptr)
  //{
  //   return;
  // }
  // QString id                               = ui.comboBox->itemData(index).toString();
  // QString id2                              = ui.comboBox->currentText();
  // int timeStep                             = id2.toInt();
  // std::vector<std::vector<Name_Loc>> table = mpWorker->GetDynamicTable();
  // ui.Name_LocWidget->clear();
  // if (table.size() > timeStep)
  //{
  //   for (int k = 0; k < table[timeStep - 1].size(); ++k)
  //   {
  //     Name_Loc& node = table[timeStep - 1][k];
  //     ui.Name_LocWidget->addItem(new QListWidgetItem(QString::fromStdString(node.name)));
  //   }
  // }
}

void vsgUI::SwapTexutre2()
{
  if (m3DRender)
  {
    m3DRender->SetTextureColorTable(mColorTable2);
  }
}

void vsgUI::SetTexture1()
{
  QString filter = tr("色表图片 (*.png)");
  QFileDialog dialog(this);
  dialog.setNameFilter(filter);
  dialog.setDirectory(QDir(QString::fromUtf8("G:/Data")));
  if (dialog.exec() == QDialog::Accepted)
  {
    mColorTable1 = dialog.selectedFiles().first();
  }
}

void vsgUI::SetTexture2()
{
  QString filter = tr("色表图片 (*.png)");
  QFileDialog dialog(this);
  dialog.setNameFilter(filter);
  dialog.setDirectory(QDir(QString::fromUtf8("G:/Data")));
  if (dialog.exec() == QDialog::Accepted)
  {
    mColorTable2 = dialog.selectedFiles().first();
  }
}

void vsgUI::ComboxFieldChange(int index)
{
  if (m3DRender)
  {
    m3DRender->SetFiledIndexShow(index);
  }
}

void vsgUI::NextField(int index)
{
  if (m3DRender)
  {
    m3DRender->SetFiledIndexShow(index);
  }
}

void vsgUI::SetAlpha(int value)
{
  if (m3DRender)
  {
    m3DRender->SetTransparency(mCurrentNode, 1 - value / 100.0f);
  }
}

void vsgUI::ShowGridCell() {}

void vsgUI::RemoveCurrentAll()
{
  if (m3DRender)
  {
    RemoveGridLayer();
    RemoveWellLayer();
    mScale = vsg::dvec3(1, 1, 1);
    ui.comboBox_Value->clear();
  }
}

void traverseTreeView(const QModelIndex& index, QTreeView* treeView, bool bCheck)
{
  // 处理当前节点
  QVariant data             = treeView->model()->data(index);
  QStandardItemModel* model = qobject_cast<QStandardItemModel*>(treeView->model());
  QStandardItem* item       = model->itemFromIndex(index);
  if (item)
  {
    if (item->isCheckable())
    {
      if (bCheck)
      {
        item->setCheckState(Qt::CheckState::Checked);
      }
      else
      {
        item->setCheckState(Qt::CheckState::Unchecked);
      }
    }
  }
  // 遍历子节点
  int childCount = treeView->model()->rowCount(index);
  for (int row = 0; row < childCount; ++row)
  {
    QModelIndex childIndex = item->child(row, 0)->index();
    traverseTreeView(childIndex, treeView, bCheck);
  }
}

void vsgUI::RemoveGridLayer()
{
  if (m3DRender)
  {
    mSelectField.clear();
    if (mTreeRoot)
    {
      traverseTreeView(mTreeRoot->index(), ui.FileTreeView, false);
    }
    m3DRender->RemoveRenderNode(mCurrentNode);
    ui.comboBox_Value->clear();
    mScale = vsg::dvec3(1, 1, 1);
  }
}

void vsgUI::RemoveWellLayer()
{
  if (m3DRender)
  {
    if (mTreeRootWell)
    {
      traverseTreeView(mTreeRootWell->index(), ui.FileTreeView, false);
    }
    m3DRender->RemoveRenderNode(mCurrentWellNode);
  }
}

void MessageStateProgreeFunction(std::string msg, int state, float per)
{
  if (gUI)
  {
    gUI->ShowStateMessageAndProgress(QString::fromStdString(msg), per);
  }
}

// 接收线程函数
void vsgUI::receiveMsgFromThread(QString msg, int state, float per)
{
  mpStateMessageLabel->setText(msg);
  progressBar->setValue(per);
  progressBar->setFormat(QString("%1\%").arg((int)per));
  if (mProgressDlg == nullptr)
  {
    mProgressDlg = new ProgressDlg(this);
  }
  mProgressDlg->ShowMessageState(msg, state, per);
  if (per >= 100)
  {
    mProgressDlg->hide();
  }
  else
  {
    mProgressDlg->show();
  }
  if (state == 10)
  {
    SetStaticOrDynamic(true);
  }
}

void vsgUI::receiveRenderData(RenderData* render, int datatype)
{
  if (m3DRender)
  {
    bool bChecked    = true;
    mNeedResetCamera = mNeedResetCamera || bChecked;
    if (datatype == 2)
    {
      m3DRender->RemoveRenderNode(mCurrentNode);
      mCurrentNode = m3DRender->AddRenderData(render, mNeedResetCamera);
    }
    else
    {
      m3DRender->RemoveRenderNode(mCurrentWellNode);
      mCurrentWellNode = m3DRender->AddRenderData(render, mNeedResetCamera);
    }
    // 新加的节点 默认 1 1 1
    mScale           = vsg::dvec3(1, 1, 1);
    mNeedResetCamera = false;
    mpWorker->DeleteRenderData(render);
    emit Apply();
  }
}

void vsgUI::SelDyValues(bool bsel) {}

void vsgUI::SelStaticValues(bool bsel) {}

void vsgUI::SetStaticOrDynamic(bool bsel)
{
  if (bsel && mpWorker)
  {
    emit RemoveGridLayer();
    emit InitDataTree();
    //  InitFilterGroup();
    //  InitFilterGroup2();
    InitFilterGroup3();
    // InitFilterGroup4();
  }
  // if (ui.radioButtonDynamic->isChecked())
  //{
  //   ui.comboBox_Value->setEnabled(true);
  // }
  // else
  //{
  //   ui.comboBox_Value->setEnabled(false);
  // }
}

void vsgUI::Apply()
{
  if (m3DRender)
  {
    double sz = ui.lineEditSZ->text().toDouble();
    if (sz <= 0)
    {
      sz = 1;
    }
    vsg::dvec3 scale = vsg::dvec3(1, 1, sz / mScale.z);
    m3DRender->SetScale(mCurrentNode, scale);
    m3DRender->SetScale(mCurrentWellNode, scale);
    mScale.z = sz;
  }
}

void vsgUI::LightSrengthUpdate() 
{
  if (m3DRender)
  {
    double l = ui.lineEditLightSrength->text().toDouble();
    m3DRender->SetLightSrength(l);
  }
}

void vsgUI::SetGridSeeDistance()
{
  if (m3DRender == nullptr)
  {
    return;
  }
  double seeDistance = ui.lineEditGridSeeDistance->text().toDouble();
  if (ui.checkBoxGridLine->isChecked())
  {
    m3DRender->SetGridLineShowDistance(mCurrentNode,seeDistance, vsg::vec3(0, 0, 0), true);
  }
  else
  {
    m3DRender->SetGridLineShowDistance(mCurrentNode, seeDistance, vsg::vec3(0, 0, 0), false);
  }
}

void vsgUI::SetGridLineShow(bool bon)
{
  ui.lineEditGridSeeDistance->setEnabled(bon);
  emit SetGridSeeDistance();
}

void vsgUI::InitFilterGroup()
{
  // if (mpWorker)
  //{
  //   CornerGrid* pGrid = mpWorker->GetGrid();
  //   vsg::ivec3 minIJK;
  //   vsg::ivec3 maxIJK;
  //   pGrid->GetIJKSize(minIJK, maxIJK);
  //   ui.listWidgetI->clear();
  //   ui.listWidgetJ->clear();
  //   ui.listWidgetK->clear();
  //   for (int i = minIJK.x; i < maxIJK.x; ++i)
  //   {
  //     QListWidgetItem* item = new QListWidgetItem(ui.listWidgetI);
  //     QCheckBox* checkbox   = new QCheckBox;
  //     checkbox->setText(QString("%1").arg(i));
  //     ui.listWidgetI->addItem(item);
  //     ui.listWidgetI->setItemWidget(item, checkbox);
  //   }
  //   for (int i = minIJK.y; i < maxIJK.y; ++i)
  //   {
  //     QListWidgetItem* item = new QListWidgetItem(ui.listWidgetJ);
  //     QCheckBox* checkbox   = new QCheckBox;
  //     checkbox->setText(QString("%1").arg(i));
  //     ui.listWidgetJ->addItem(item);
  //     ui.listWidgetJ->setItemWidget(item, checkbox);
  //   }
  //   for (int i = minIJK.z; i < maxIJK.z; ++i)
  //   {
  //     QListWidgetItem* item = new QListWidgetItem(ui.listWidgetK);
  //     QCheckBox* checkbox   = new QCheckBox;
  //     checkbox->setText(QString("%1").arg(i));
  //     ui.listWidgetK->addItem(item);
  //     ui.listWidgetK->setItemWidget(item, checkbox);
  //   }
  // }
}

void vsgUI::Filter()
{
  // if (mpWorker)
  //{
  //   CornerGrid* pGrid = mpWorker->GetGrid();
  //   if (pGrid->GetGridNum() > 10000000)
  //   {
  //     QMessageBox::information(nullptr, "提示", "千万以上的网格还未实现");
  //     return;
  //   }
  //   std::vector<int> Iids;
  //   std::vector<int> Jids;
  //   std::vector<int> Kids;
  //   for (int i = 0; i < ui.listWidgetI->count(); i++)
  //   {
  //     QListWidgetItem* item = ui.listWidgetI->item(i);
  //     // 将QWidget 转化为QCheckBox  获取第i个item 的控件
  //     QCheckBox* checkbox = static_cast<QCheckBox*>(ui.listWidgetI->itemWidget(item));
  //     bool bChecked       = checkbox->checkState() == Qt::CheckState::Checked;
  //     if (bChecked)
  //     {
  //       Iids.push_back(i);
  //     }
  //   }
  //   for (int i = 0; i < ui.listWidgetJ->count(); i++)
  //   {
  //     QListWidgetItem* item = ui.listWidgetJ->item(i);
  //     // 将QWidget 转化为QCheckBox  获取第i个item 的控件
  //     QCheckBox* checkbox = static_cast<QCheckBox*>(ui.listWidgetJ->itemWidget(item));
  //     bool bChecked       = checkbox->checkState() == Qt::CheckState::Checked;
  //     if (bChecked)
  //     {
  //       Jids.push_back(i);
  //     }
  //   }
  //   for (int i = 0; i < ui.listWidgetK->count(); i++)
  //   {
  //     QListWidgetItem* item = ui.listWidgetK->item(i);
  //     // 将QWidget 转化为QCheckBox  获取第i个item 的控件
  //     QCheckBox* checkbox = static_cast<QCheckBox*>(ui.listWidgetK->itemWidget(item));
  //     bool bChecked       = checkbox->checkState() == Qt::CheckState::Checked;
  //     if (bChecked)
  //     {
  //       Kids.push_back(i);
  //     }
  //   }
  //   pGrid->ShowIJKIDs(Iids, Jids, Kids);

  //  emit ShowGrid();
  //}
}
void vsgUI::FilterDebug()
{
  //if (mpWorker)
  //{
  //  CornerGrid* pGrid = mpWorker->GetGrid();
  //  //pGrid->FilterAttDebug();
  //  emit ShowGrid();
  //}
}
void vsgUI::InitFilterGroup2()
{
  // if (mpWorker)
  //{
  //   CornerGrid* pGrid = mpWorker->GetGrid();
  //   vsg::ivec3 minIJK;
  //   vsg::ivec3 maxIJK;
  //   pGrid->GetIJKSize(minIJK, maxIJK);
  //   ui.lineEdit_FilterXMin->setText(QString("%1").arg(minIJK.x));
  //   ui.lineEdit_FilterXMax->setText(QString("%1").arg(maxIJK.x));

  //  ui.lineEdit_FilterYMin->setText(QString("%1").arg(minIJK.y));
  //  ui.lineEdit_FilterYMax->setText(QString("%1").arg(maxIJK.y));

  //  ui.lineEdit_FilterZMin->setText(QString("%1").arg(minIJK.z));
  //  ui.lineEdit_FilterZMax->setText(QString("%1").arg(maxIJK.z));
  //}
}

void vsgUI::Filter2()
{
  // if (mpWorker)
  //{
  //   CornerGrid* pGrid = mpWorker->GetGrid();
  //   // pGrid->FilterAtt();
  //   vsg::ivec3 minIJK;
  //   vsg::ivec3 maxIJK;
  //   pGrid->GetIJKSize(minIJK, maxIJK);

  //  int xMin = ui.lineEdit_FilterXMin->text().toInt();
  //  int xMax = ui.lineEdit_FilterXMax->text().toInt();

  //  int yMin = ui.lineEdit_FilterYMin->text().toInt();
  //  int yMax = ui.lineEdit_FilterYMax->text().toInt();

  //  int zMin = ui.lineEdit_FilterZMin->text().toInt();
  //  int zMax = ui.lineEdit_FilterZMax->text().toInt();
  //  ////显示剖面 i = 0;
  //  pGrid->FilterShowIJKSection(xMin, xMax, yMin, yMax, zMin, zMax);
  //}
  // emit ShowGrid();
}

void vsgUI::InitFilterGroup3()
{
  if (mpWorker)
  {
    CornerGrid* pGrid = mpWorker->GetGrid();
    vsg::ivec3 minIJK;
    vsg::ivec3 maxIJK;
    pGrid->GetIJKSize(minIJK, maxIJK);

    ui.label_IMin->setText(QString("%1").arg(minIJK.x));
    ui.label_JMin->setText(QString("%1").arg(minIJK.y));
    ui.label_KMin->setText(QString("%1").arg(minIJK.z));

    ui.label_IMax->setText(QString("%1").arg(maxIJK.x));
    ui.label_JMax->setText(QString("%1").arg(maxIJK.y));
    ui.label_KMax->setText(QString("%1").arg(maxIJK.z));

    ui.lineEdit_StartI->setText(QString("%1").arg(minIJK.x));
    ui.lineEdit_StartJ->setText(QString("%1").arg(minIJK.y));
    ui.lineEdit_StartK->setText(QString("%1").arg(minIJK.z));

    ui.lineEdit_EndI->setText(QString("%1").arg(maxIJK.x));
    ui.lineEdit_EndJ->setText(QString("%1").arg(maxIJK.y));
    ui.lineEdit_EndK->setText(QString("%1").arg(maxIJK.z));
  }
}

void vsgUI::Filter3()
{
  if (mpWorker == nullptr)
  {
    return;
  }
  int IStart = ui.lineEdit_StartI->text().toInt();
  int JStart = ui.lineEdit_StartJ->text().toInt();
  int KStart = ui.lineEdit_StartK->text().toInt();

  int IStep = ui.lineEdit_IStep->text().toInt();
  int JStep = ui.lineEdit_JStep->text().toInt();
  int KStep = ui.lineEdit_KStep->text().toInt();

  int IEnd = ui.lineEdit_EndI->text().toInt();
  int JEnd = ui.lineEdit_EndJ->text().toInt();
  int KEnd = ui.lineEdit_EndK->text().toInt();

  int iMin = ui.label_IMin->text().toInt();
  int jMin = ui.label_JMin->text().toInt();
  int kMin = ui.label_KMin->text().toInt();

  int iMax = ui.label_IMax->text().toInt();
  int jMax = ui.label_JMax->text().toInt();
  int kMax = ui.label_KMax->text().toInt();
  if (iMax < iMin || jMax < jMin || kMax < kMin)
  {
    QMessageBox::information(nullptr, "提示", "参数设置错误,请检查");
    return;
  }

  std::vector<int> Iids;
  std::vector<int> Jids;
  std::vector<int> Kids;
  mbFilter = false;
  if (ui.checkBox_FilterI->checkState() == Qt::CheckState::Checked)
  {
    for (int i = IStart; i <= IEnd; i += IStep)
    {
      Iids.push_back(i);
      if (IStep == 0)
      {
        break;
      }
    }
    mbFilter = true;
  }
  if (ui.checkBox_FilterJ->checkState() == Qt::CheckState::Checked)
  {
    for (int i = JStart; i <= JEnd; i += JStep)
    {
      Jids.push_back(i);
      if (JStep == 0)
      {
        break;
      }
    }
    mbFilter = true;
  }
  if (ui.checkBox_FilterK->checkState() == Qt::CheckState::Checked)
  {
    for (int i = KStart; i <= KEnd; i += KStep)
    {
      Kids.push_back(i);
      if (KStep == 0)
      {
        break;
      }
    }
    mbFilter = true;
  }
  if (mbFilter)
  {
    CornerGrid* pGrid = mpWorker->GetGrid();
    pGrid->ShowIJKIDs(Iids, Jids, Kids);
    emit ShowGrid();
  }
}

void vsgUI::InitFilterGroup4()
{
  // if (mpWorker)
  //{
  //   CornerGrid* pGrid = mpWorker->GetGrid();
  //   vsg::ivec3 minIJK;
  //   vsg::ivec3 maxIJK;
  //   pGrid->GetIJKSize(minIJK, maxIJK);

  //  ui.label_IMin_2->setText(QString("%1").arg(minIJK.x));
  //  ui.label_JMin_2->setText(QString("%1").arg(minIJK.y));
  //  ui.label_KMin_2->setText(QString("%1").arg(minIJK.z));

  //  ui.label_IMax_2->setText(QString("%1").arg(maxIJK.x));
  //  ui.label_JMax_2->setText(QString("%1").arg(maxIJK.y));
  //  ui.label_KMax_2->setText(QString("%1").arg(maxIJK.z));
  //}
}

void vsgUI::Filter4() {}

void vsgUI::FilterReset()
{
  if (mpWorker && mbFilter)
  {
    CornerGrid* pGrid = mpWorker->GetGrid();
    if (pGrid)
    {
      pGrid->ResetFilter();
      emit ShowGrid();
    }
  }
}

void vsgUI::SelAll_I()
{
  // for (int i = 0; i < ui.listWidgetI->count(); i++)
  //{
  //   QListWidgetItem* item = ui.listWidgetI->item(i);
  //   QCheckBox* checkbox   = static_cast<QCheckBox*>(ui.listWidgetI->itemWidget(item));
  //   checkbox->setChecked(true);
  // }
}

void vsgUI::ReSel_I()
{
  // for (int i = 0; i < ui.listWidgetI->count(); i++)
  //{
  //   QListWidgetItem* item = ui.listWidgetI->item(i);
  //   // 将QWidget 转化为QCheckBox  获取第i个item 的控件
  //   QCheckBox* checkbox = static_cast<QCheckBox*>(ui.listWidgetI->itemWidget(item));
  //   bool bChecked       = checkbox->checkState() == Qt::CheckState::Checked;
  //   checkbox->setChecked(!bChecked);
  // }
}

void vsgUI::SelAll_J()
{
  // for (int i = 0; i < ui.listWidgetJ->count(); i++)
  //{
  //   QListWidgetItem* item = ui.listWidgetJ->item(i);
  //   QCheckBox* checkbox   = static_cast<QCheckBox*>(ui.listWidgetJ->itemWidget(item));
  //   checkbox->setChecked(true);
  // }
}

void vsgUI::ReSel_J()
{
  // for (int i = 0; i < ui.listWidgetJ->count(); i++)
  //{
  //   QListWidgetItem* item = ui.listWidgetJ->item(i);
  //   // 将QWidget 转化为QCheckBox  获取第i个item 的控件
  //   QCheckBox* checkbox = static_cast<QCheckBox*>(ui.listWidgetJ->itemWidget(item));
  //   bool bChecked       = checkbox->checkState() == Qt::CheckState::Checked;
  //   checkbox->setChecked(!bChecked);
  // }
}

void vsgUI::SelAll_K()
{
  // for (int i = 0; i < ui.listWidgetK->count(); i++)
  //{
  //   QListWidgetItem* item = ui.listWidgetK->item(i);
  //   QCheckBox* checkbox   = static_cast<QCheckBox*>(ui.listWidgetK->itemWidget(item));
  //   checkbox->setChecked(true);
  // }
}

void vsgUI::ReSel_K()
{
  // for (int i = 0; i < ui.listWidgetK->count(); i++)
  //{
  //   QListWidgetItem* item = ui.listWidgetK->item(i);
  //   // 将QWidget 转化为QCheckBox  获取第i个item 的控件
  //   QCheckBox* checkbox = static_cast<QCheckBox*>(ui.listWidgetK->itemWidget(item));
  //   bool bChecked       = checkbox->checkState() == Qt::CheckState::Checked;
  //   checkbox->setChecked(!bChecked);
  // }
}

void vsgUI::ResetScene()
{
  if (m3DRender)
  {
    m3DRender->ResetScene();
  }
}

void vsgUI::ClearScene()
{
  if (m3DRender)
  {
    m3DRender->RemoveRenderNode(mCurrentNode);
    m3DRender->RemoveRenderNode(mCurrentWellNode);
  }
}

void vsgUI::SelFilterI(bool bsel)
{
  ui.lineEdit_StartI->setEnabled(bsel);
  ui.lineEdit_IStep->setEnabled(bsel);
  ui.lineEdit_EndI->setEnabled(bsel);
}

void vsgUI::SelFilterJ(bool bsel)
{
  ui.lineEdit_StartJ->setEnabled(bsel);
  ui.lineEdit_JStep->setEnabled(bsel);
  ui.lineEdit_EndJ->setEnabled(bsel);
}

void vsgUI::SelFilterK(bool bsel)
{
  ui.lineEdit_StartK->setEnabled(bsel);
  ui.lineEdit_KStep->setEnabled(bsel);
  ui.lineEdit_EndK->setEnabled(bsel);
}

void vsgUI::InitDataTree()
{
  if (mpWorker == nullptr)
  {
    return;
  }
  CornerGrid* pGrid = mpWorker->GetGrid();
  std::string path  = pGrid->GetFilePath();

  mTreeRoot->removeRow(0);

  QStandardItem* childLayer = new QStandardItem(QString::fromStdString(path));
  QIcon icon(":/vsgUI/Grid.png");
  childLayer->setIcon(icon);
  childLayer->setCheckable(true);
  SelectField selV;
  selV.dataType = NODE_GRIDLAYER;
  childLayer->setData(QVariant::fromValue(selV));
  childLayer->setCheckState(Qt::CheckState::Checked);
  mTreeRoot->appendRow(childLayer);

  mSelectField.clear();
  ui.comboBox_Value->clear();

  if (ui.radioButtonStatic->isChecked())
  {
    QStandardItem* childStaticValueNode = new QStandardItem("静态属性");
    childStaticValueNode->setIcon(QIcon(":/vsgUI/StaticAtt.png"));
    SelectField selV;
    selV.dataType = NODE_GRIDFIELDTYPE;
    childStaticValueNode->setData(QVariant::fromValue(selV));

    childLayer->appendRow(childStaticValueNode);
    std::vector<Name_Loc> table1 = mpWorker->GetStaticTable();
    // 静态属性
    for (int i = 0; i < table1.size(); ++i)
    {
      Name_Loc& node = table1[i];
      if (node.name == "GRID_VTX" || node.name == "NODE_LIST" || node.name == "GRIDINFO")
      {
        continue;
      }
      if (node.name == "XCOORD" || node.name == "YCOORD" || node.name == "N2GMAP" || node.name == "G2NMAP")
      {
        continue;
      }
      if (node.name == "DX" || node.name == "DY" || node.name == "DZ")
      {
        continue;
      }
      if (node.length != mpWorker->GetGrid()->GetGridNum())
      {
        continue;
      }
      QStandardItem* childItemTimeField = new QStandardItem(QString::fromStdString(table1[i].name));
      childItemTimeField->setCheckable(true);
      childItemTimeField->setIcon(QIcon(":/vsgUI/Field.png"));
      SelectField selV;
      selV.id       = 0;
      selV.dataType = NODE_GRIDFIELD;
      selV.field    = QString::fromStdString(table1[i].name);
      childItemTimeField->setData(QVariant::fromValue(selV));

      childStaticValueNode->appendRow(childItemTimeField);
    }
  }
  if (ui.radioButtonDynamic->isChecked())
  {
    QStandardItem* childDyValueNode = new QStandardItem("动态属性");
    // child22->setCheckable(true);
    childDyValueNode->setIcon(QIcon(":/vsgUI/DyAtt.png"));
    SelectField selV;
    selV.dataType = NODE_GRIDFIELDTYPE;
    childDyValueNode->setData(QVariant::fromValue(selV));
    childLayer->appendRow(childDyValueNode);
    // 动态属性
    std::vector<std::vector<Name_Loc>> table = mpWorker->GetDynamicTable();
    for (int k = 0; k < table.size(); ++k)
    {
      // 时间
      QStandardItem* childItemTime = new QStandardItem(QString("%1").arg(k + 1));
      SelectField selV;
      selV.dataType = NODE_GRIDTIME;
      childItemTime->setData(QVariant::fromValue(selV));
      childItemTime->setIcon(QIcon(":/vsgUI/Time.png"));
      // 属性
      for (int i = 0; i < table[k].size(); ++i)
      {
        if (table[k][i].length != mpWorker->GetGrid()->GetGridNum())
        {
          continue;
        }
        QStandardItem* childItemTimeField = new QStandardItem(QString::fromStdString(table[k][i].name));
        childItemTimeField->setCheckable(true);
        childItemTimeField->setIcon(QIcon(":/vsgUI/Field.png"));

        SelectField selV;
        selV.id       = k;
        selV.dataType = NODE_GRIDFIELD;
        selV.time     = QString("%1").arg(table[k][i].time);
        selV.field    = QString::fromStdString(table[k][i].name);
        childItemTimeField->setData(QVariant::fromValue(selV));

        childItemTime->appendRow(childItemTimeField);
      }
      childDyValueNode->appendRow(childItemTime);
    }
  }

  ui.FileTreeView->expandAll();
}

void vsgUI::onCustomContextMenuRequested(const QPoint& pos)
{
  // 获取发送信号的对象并转换为 QTreeView
  QTreeView* treeView = qobject_cast<QTreeView*>(sender());
  if (!treeView)
    return;

  // 获取鼠标点击位置的索引
  QModelIndex index = treeView->indexAt(pos);
  if (!index.isValid())
    return;
  // 创建右键菜单
  QMenu contextMenu(this);
  // 添加菜单项
  QAction* action1 = contextMenu.addAction("添加到视图");

  //  连接菜单项的触发事件
  connect(action1, &QAction::triggered, this, [this, index]() {
    // 获取选中节点的数据
    QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui.FileTreeView->model());
    QStandardItem* item       = model->itemFromIndex(index);
    if (m3DRender == nullptr)
    {
      return;
    }
    SelectField selItem = item->data().value<SelectField>();
    if (selItem.dataType == NODE_GRIDLAYER || selItem.dataType == NODE_GRIDFIELDTYPE || selItem.dataType == NODE_GRIDTIME
        || selItem.dataType == NODE_GRIDFIELD)
    {
      if (mSelectField.size() < 1)
      {
        QMessageBox::information(nullptr, "提示", "选择一个或至多4个属性");
        return;
      }
      emit ShowGrid();
    }
    else if (/*selItem.dataType == NODE_WELLFIELDTYPE || selItem.dataType == NODE_WELLTIME
             || selItem.dataType == */
             NODE_WELLFIELD)
    {
      // 井数据
      // QMessageBox::information(nullptr, "提示", +"添加井数据到视图");
      QList<QString> selFields;
      selFields.push_back(selItem.field);
      if (mpWorker)
      {
        mpWorker->wait();
        mpWorker->SetWorkType(3);
        mpWorker->SetWellPathAndField(item->parent()->text(), selFields);
        mpWorker->start();
      }
    }
  });

  // connect(action2, &QAction::triggered, this,
  //         [this, index]() { QMessageBox::information(this, "Action 2", "Action 2 triggered on " + index.data().toString()); });
  //  显示右键菜单

  contextMenu.exec(treeView->viewport()->mapToGlobal(pos));
}

void vsgUI::TreeSelect(const QModelIndex& index)
{
  // 获取选中节点的数据
  QStandardItemModel* model = qobject_cast<QStandardItemModel*>(ui.FileTreeView->model());
  QStandardItem* item       = model->itemFromIndex(index);
  if (m3DRender == nullptr)
  {
    return;
  }
  if (item->parent() == mTreeRoot)
  {
    m3DRender->SetVisible(mCurrentNode, item->checkState() == Qt::CheckState::Checked);
    return;
  }
  SelectField selItem = item->data().value<SelectField>();
  if (selItem.dataType == NODE_GRIDLAYER || selItem.dataType == NODE_GRIDFIELDTYPE || selItem.dataType == NODE_GRIDTIME
      || selItem.dataType == NODE_GRIDFIELD)
  {
    // 必须选择属性 叶子节点
    if (item->hasChildren())
    {
      // 可见性
      return;
    }
    bool bCheck = item->checkState() == Qt::CheckState::Checked;
    QList<SelectField> temSel;
    for (int k = 0; k < mSelectField.size(); ++k)
    {
      if (mSelectField[k].item == item && item->checkState() == Qt::CheckState::Unchecked)
      {
        continue;
      }
      temSel.push_back(mSelectField[k]);
    }
    mSelectField = temSel;

    QString text = item->text();
    if (bCheck)
    {
      bool bFind = false;
      for (int k = 0; k < mSelectField.size(); ++k)
      {
        if (mSelectField[k].item == item)
        {
          bFind = true;  
          break;
        }
      }
      if (!bFind)
      {
        if (mSelectField.size() >= 4)
        {
          QMessageBox::information(nullptr, "提示", "不支持4个以上的属性处理");
          item->setCheckState(Qt::CheckState::Unchecked);
          return;
        }
        selItem.item = item;
        mSelectField.push_back(selItem);
      }
    }

  }
  else if (selItem.dataType == NODE_WELLLAYER || selItem.dataType == NODE_WELLFIELDTYPE || selItem.dataType == NODE_WELLTIME
           || selItem.dataType == NODE_WELLFIELD)
  {
    // 井数据
    // QMessageBox::information(nullptr, "提示", "显示与隐藏井数据");
    m3DRender->SetVisible(mCurrentWellNode /*selItem.node*/, item->checkState() == Qt::CheckState::Checked);
  }
}

void vsgUI::OpenFile()
{
  QString filter = tr("网格数据 geom.bin (*.bin)");
  QFileDialog dialog(this);
  dialog.setNameFilter(filter);
  dialog.setDirectory(QDir(QString::fromUtf8("G:/Data")));
  if (dialog.exec() == QDialog::Accepted)
  {
    QString fileName = "I:\\2024.10.15\\Data\\SPE10_geom.bin";  //
    fileName         = dialog.selectedFiles().first();
    QString srcFile  = fileName;
    QString geoPath  = fileName.left(fileName.length() - QString("_geom.bin").length());
    QString stuPath  = geoPath + QString("_stu.bin");
    if (!QFile::exists(stuPath))
    {
      QMessageBox::information(nullptr, "提示", stuPath + "文件不存在");
      return;
    }
    if (mpWorker)
    {
      mpWorker->wait();
    }
    mTreeRoot->removeRow(0);
    RemoveGridLayer();

    // mTreeRootWell->removeRow(0);

    InitWorkThread();
    // 数据量比较大    直接先进行加载
    if (mpWorker)
    {
      mGridPath = geoPath;
      mpWorker->SetGridPathAndField(geoPath, mSelectField);

      mpWorker->SetWorkType(1);
      mpWorker->start();
    }
    mNeedResetCamera = true;
  }
}
void vsgUI::InitWorkThread()
{
  if (mpWorker == nullptr)
  {
    mpWorker = new Worker(MessageStateProgreeFunction, this);
    // 接收子线程发来的数据
    connect(mpWorker, &Worker::sendMsgToMain, this, &vsgUI::receiveMsgFromThread);
    connect(mpWorker, &Worker::SendDataToMain, this, &vsgUI::receiveRenderData);
  }
}
void vsgUI::OpenWell()
{
  QString filter = tr("井数据 (*.out)");
  QFileDialog dialog(this);
  dialog.setNameFilter(filter);
  dialog.setDirectory(QDir(QString::fromUtf8("G:/Data")));
  if (dialog.exec() == QDialog::Accepted)
  {
    InitWorkThread();

    QString FileName = dialog.selectedFiles().first();
    QIcon icon(":/vsgUI/well.png");
    QStandardItem* FileLayer = new QStandardItem(FileName);
    FileLayer->setIcon(icon);
    FileLayer->setCheckable(true);
    SelectField selV;
    selV.dataType = NODE_WELLLAYER;
    FileLayer->setData(QVariant::fromValue(selV));
    FileLayer->setCheckState(Qt::CheckState::Checked);

    mTreeRootWell->removeRow(0);
    RemoveWellLayer();

    mTreeRootWell->appendRow(FileLayer);

    // QMessageBox::information(nullptr, "提示", FileName);
    //  时间  井号  井层数-每层属性
    QMap<int, QMap<QString, QVector<WellPoint>>> wells;
    QString error2;
    WellPoint::readWell(FileName, wells, error2);
    QMap<int, QMap<QString, QVector<WellPoint>>>::iterator it;
    for (it = wells.begin(); it != wells.end(); ++it)
    {
      QMap<QString, QVector<WellPoint>>& well = it.value();
      QMap<QString, QVector<WellPoint>>::iterator itWell;
      QMap<QString, QVector<WellPoint>>::iterator itWellBegin = well.begin();
      QMap<QString, QVector<WellPoint>>::iterator itWellEnd   = well.end();
      int id                                                  = 1;
      for (itWell = itWellBegin; itWell != itWellEnd; ++itWell, ++id)
      {
        QVector<WellPoint>& wellLayers = itWell.value();
        for (int kLayer = 0; kLayer < wellLayers.size() - 1; ++kLayer)
        {
          WellPoint& layer = wellLayers[kLayer];
          QMap<QString, double>::iterator itF;
          QMap<QString, double>::iterator itFBegin = layer.properties.begin();
          QMap<QString, double>::iterator itFEnd   = layer.properties.end();
          for (itF = itFBegin; itF != itFEnd; ++itF)
          {
            QStandardItem* childItemTimeField = new QStandardItem(itF.key());
            childItemTimeField->setCheckable(true);
            childItemTimeField->setIcon(QIcon(":/vsgUI/Field.png"));
            SelectField selV;
            selV.id       = -1;
            selV.dataType = NODE_WELLFIELD;
            selV.field    = itF.key();
            childItemTimeField->setData(QVariant::fromValue(selV));
            FileLayer->appendRow(childItemTimeField);
          }
          break;
        }
        break;
      }
      break;
    }
  }
}